package com.itheima.springboottilasmanager.Aop;

import com.itheima.springboottilasmanager.mapper.OperateLogMapper;
import com.itheima.springboottilasmanager.pojo.domain.OperateLog;
import com.itheima.springboottilasmanager.util.ApplicationContext;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

//@Aspect
@Component
public class OperateLogAspect {
//    切入点表达式使用annotation,配合log标记
//    方法一，通过请求获取ID
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private OperateLogMapper operateLogMapper;
    @Around("@annotation( com.itheima.springboottilasmanager.anonotation.log)")
    public  Object recordLog(ProceedingJoinPoint jpt) throws Throwable {//连接点对象（封装了目标方法的所有信息）
//        1.创建日志对象
        OperateLog log = new OperateLog();
//
        log.setOperateTime(LocalDateTime.now());
//        设置目标方法相关的信息
        log.setClassName(jpt.getTarget().getClass().getName());//设置目标方法所属的类信息
        log.setMethodName(jpt.getSignature().getName());//设置目标方法名称
        log.setMethodParams(Arrays.toString(jpt.getArgs()));//设置目标方法参数
        //设置目标方法返回值
//        设置目标方法的结果和耗时
        long start = System.currentTimeMillis();
        Object result = jpt.proceed();
        long end = System.currentTimeMillis();
        log.setCostTime(end - start);
        log.setReturnValue(jpt.proceed().toString());
//        设置操作者的信息
//        利用容器创建一个线程，将id保存在当前线程中
//        String token = request.getHeader("token");
//        Claims claims = JwtUtils.parseJWT(token);
//        Integer id = (Integer) claims.get("id");
//        log.setOperateEmpId(id)
        log.setOperateEmpId(ApplicationContext.getEmpId());
        operateLogMapper.insert(log);
        ApplicationContext.clear();
        return result;
    }
}
